<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form ref="queryRef" :model="pageParams" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
            placeholder="请输入品牌名称"
            clearable
            v-model = "pageParams.name"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['product:brand:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['product:brand:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['product:brand:remove']"
        >删除</el-button>
      </el-col>


      <!-- 功能按钮栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>


    </el-row>


    <!-- 数据展示表格 -->
    <el-table :data="brandList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌名称" prop="name" width="200"/>
      <el-table-column label="品牌图标" prop="logo" #default="scope">
        <img :src="scope.row.logo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope"><!-- scope 插槽：存放迭代一行数据，看做成brand对象，要想渠取到这个brand对象，使用scope.row-->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:brand:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:brand:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[2, 5, 10, 20]"
        v-model:page="pageParams.pageNum"
        v-model:limit="pageParams.pageSize"
        @pagination="getList"
    />


    <!-- 新增或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="brandRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload
              class="avatar-uploader"
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>

<script setup name="Brand">


//----组件导入区域-----------------------------------------------------
//import { ref,reactive,toRefs} from 'vue'
import { listBrand,addBrand,getBrand,updateBrand,deleteBrand } from '@/api/product/brand.js'
import { getToken } from '@/utils/auth'
import { ElMessage,ElMessageBox } from 'element-plus'

//----变量声明区域-----------------------------------------------

const { proxy } = getCurrentInstance();  //  proxy 就相当与vue对象。看做this

//定义分页列表数据模型
const brandList = ref([]);
//定义列表总记录数模型
const total = ref(2);
//定义表格加载效果模型
const loading = ref(true)

//Vue 3 中的两种响应式数据绑定方式：reactive 和 ref
//ref定义：基本数据类型，适用于简单的响应式数据
//reactive定义：对象（或数组）数据类型，则适用于复杂对象或数组的响应式数据
const data = reactive({
  pageParams: {
    pageNum: 1,
    pageSize: 2,
    name:null
  },
  form:{
    name:null,
    logo:null
  },
  imgUpload:{
    url: import.meta.env.VITE_APP_BASE_API + '/file/upload',   //   /dev-api/file/upload
    headers:{ //文件上传同步请求，需要自己手动绑定请求头。如果是异步请求。request.js的请求拦截器会自动绑定请求头。
      Authorization: 'Bearer ' + getToken() // 从cookie中获取登录令牌
    }
  },
  rules: {
    //校验属性名称与表单属性名称一致。否则，校验出现问题：校验提示后，给与正确值，提示不消失。
    name: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
    logo: [{ required: true, message: "品牌LOGO不能为空", trigger: "blur" }],
  }
})

const { pageParams,form,imgUpload,rules} = toRefs(data) //将data中数据转换成一个一个ref的响应式数据。

//console.log("====="+data.pageParams.pageNum)
//console.log("-----"+pageParams.value.pageNum)
//控制添加对话框是否显示
const open = ref(false)
const title = ref('')

//控制批量删除的可用状态
const multiple = ref(true)  //  true禁用

//控制修改按钮可用状态
const single = ref(true) // true禁用
//按钮组中：修改和批量删除使用
const ids = ref([])

//定义隐藏搜索控制模型
const showSearch = ref(true);

//----分页开始-----------------------------------------------

function getList(){
  loading.value = true

  //const {total,rows} = listBrand(pageParams.value)  //结构


  listBrand(pageParams.value).then(result=>{  //处理异步请求成功    result==>  TableDataInfo
    brandList.value = result.rows
    total.value = result.total
    loading.value = false
  }).catch((e)=>{//处理异步请求失败
    console.log(e)
  })
}

getList()

//搜索按钮绑定单击事件。
function handleQuery(){
  getList();
}

//重置搜索表单
/*function reset(){
  pageParams.value.name = null
  pageParams.value.pageNum = 1
  pageParams.value.pagesize = 2
  handleQuery()
}*/
function reset(){
  //debugger
  proxy.resetForm('queryRef')
  pageParams.value.pageNum = 1
  handleQuery()
}

//----添加 开始-------------------------------------

//弹出添加表单
function handleAdd(){
  open.value = true
  title.value = '添加品牌'
  resetForm()
}

//上传成功后的回调处理
function handleAvatarSuccess(result, uploadFile){ //  result  ->  R      R中有数据:[msg,code,data]   data-> SysFile[name,url]
  console.log(result)
  console.log(result)
  form.value.logo = result.data.url;
}

//只做添加
/*function submitForm(){
  addBrand(form.value).then(result=>{
    ElMessage.success("保存成功")
    open.value = false
    getList()
  }).catch(e=>{
    ElMessage.error("保存失败")
  })
}*/

function resetForm(){
  // form.value.name=null
  // form.value.logo=null
  // form.value.id=nul
  // form.value = {
  //   id:null, // 修改和添加使用是同一个表单。
  //   name:null,
  //   logo:null
  // }
  proxy.resetForm("brandRef");
  console.log("===>>>>>>>>>>"+form.value)
  debugger
}

function cancel(){
  resetForm()
  open.value = false
}

//表格后面修改按钮单击事件处理，弹出对话框（修改表单）
function handleUpdate(row){ // row看做brand对象   {id:1,name:'小米',logo:'url地址'}

  resetForm()

  open.value = true
  title.value = '修改品牌'

  //查询数据
  const _id = row.id || ids.value
  getBrand(_id).then(result=>{  //controller方法返回AjaxResult extends HashMap     [code,msg,data]
    form.value = result.data
  }).catch(e=>{

  })

}

//添加和修改合并一个事件处理。添加没有id值；修改提交有id值。
function submitForm(){

  proxy.$refs['brandRef'].validate(valid=>{
    if(valid){ //表单校验成功。
      //添加
      if(form.value.id == null){ //值不存在是null,就是false;  非null的值都转换为true
        addBrand(form.value).then(result=>{
          ElMessage.success("保存成功")
          open.value = false
          getList()
        }).catch(e=>{
          ElMessage.error("保存失败")
        })
      }else{ //修改
        updateBrand(form.value).then(result=>{
          ElMessage.success("修改成功")
          open.value = false
          getList()
        }).catch(e=>{
          ElMessage.error("修改失败")
        })
      }
    }else{
      proxy.$modal.msgError('表单校验失败')
    }
  })
}


/*function handleDelete(row){
  debugger
  console.log("====>>>    "+ids.value)
  const _id = row.id || ids.value
  console.log("---->>>    "+_id)

  ElMessageBox.confirm('您确定要删除数据吗?','警告',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(()=>{ //确定按钮执行then
    deleteBrand(_id).then(result=>{
      ElMessage.success("删除成功")
      getList()
    }).catch(e=>{
      ElMessage.error("删除失败")
    })
  }).catch((e)=>{ //取消按钮执行catch
    if(e =='cancel'){
      ElMessage.info("取消删除")
    }else{
      ElMessage.error('删除异常')
    }
  })
}*/


function handleDelete(row){
  debugger
  console.log("====>>>    "+ids.value)
  const _id = row.id || ids.value
  console.log("---->>>    "+_id)

  proxy.$modal.confirm('您确定要删除数据吗?').then(()=>{ //确定按钮执行then
    deleteBrand(_id).then(result=>{
      proxy.$modal.msgSuccess("删除成功")
      getList()
    }).catch(e=>{
      proxy.$modal.msgError("删除失败")
    })
  }).catch((e)=>{ //取消按钮执行catch
    if(e =='cancel'){
      proxy.$modal.msg("取消删除")
    }else{
      proxy.$modal.msgError("删除失败")
    }
  })
}

//列表复选框被勾选或取消勾选都会执行当前函数。
function handleSelectionChange(selection){ //  selection表示打钩标体复选框  行对象  集合
  console.log(selection)
  //ids.value = selection.map(item => {return item.id} ) //取所有行的id值
  ids.value = selection.map(item => item.id) //取所有行的id值
  console.log(ids.value)
  single.value = selection.length != 1
  //multiple.value = selection.length == 0
  multiple.value = !selection.length
}



</script>






<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>